# coding=utf-8

from flask import request
from flask import render_template
from flask import redirect, url_for, flash
from flask import session, g
from werkzeug import secure_filename
from flask_login import login_required

import os
import time
import json
from datetime import datetime
from app import app
from app.utils import genorate_image
from app.oauth_client import OAuthQQ
from . import settings
from .forms import SentenceForm
from app import db, models
from flask_login import current_user, login_user, logout_user, login_manager

'''
@app.before_request
def before_request():
    g.user = current_user
    if g.user.is_authenticated():
        g.user.last_seen = datetime.utcnow()
        db.session.add(g.user)
        db.session.commit()
'''

# 首页
@app.route('/', methods=['GET', 'POST'])
def home():
    if 'user' in session:
        user = session['user']
        username = session['username']
    else:
        username = 'Guest'
        user = None

    form = SentenceForm(formdata=request.form)
    if form.validate_on_submit():
        if request.form['g_img'] == '横排图片':
            genorate_image(form.content.data, font_path='app/images/font.TTF', size=24, bg_path='app/images/timg.jpg')
        else:
            genorate_image(form.content.data, font_path='app/images/font.TTF', size=72, direction='vertical')
        return render_template('showimg.html', val1=time.time())
    else:
        return render_template('index.html', title='输入句子', form=form, user=user, username=username)


# 登录 20190315


@app.route('/qq_login')
def qq_login():
    oauth_qq = OAuthQQ(settings.QQ_APP_ID, settings.QQ_KEY, settings.QQ_RECALL_URL)

    # 获取 得到Authorization Code的地址
    url = oauth_qq.get_auth_url()
    # 重定向到授权页面
    return redirect(url)


# 第三方QQ登录，回调函数


@app.route('/qqLogin')
def qqLogin():
    """登录之后，会跳转到这里。需要判断code和state"""
    request_code = request.args.get('code')
    oauth_qq = OAuthQQ(settings.QQ_APP_ID, settings.QQ_KEY, settings.QQ_RECALL_URL)

    # 获取access_token
    access_token = oauth_qq.get_access_token(request_code)
    time.sleep(0.05)  # 稍微休息一下，避免发送urlopen的10060错误
    open_id = oauth_qq.get_open_id()

    # 显示登录信息
    user = oauth_qq.get_qq_info()
    session['username'] = user['nickname']
    session['user'] = user

    # 检查open_id是否存在
    oauth_user = models.SocialAuthUsersocialauth.query.filter(
        models.SocialAuthUsersocialauth.openid == str(open_id)).first()
    if oauth_user:
        # 存在则获取对应的用户，并更新Social_auth_usersocialauth表中的extra_data字段。
        oauth_user.extra_data = json.dumps(user)
        db.session.commit()
    else:
        # 不存在，存储到SocialAuthUsersocialauth表中
        oauth_user = models.SocialAuthUsersocialauth(provider='qq', openid=open_id, extra_data=json.dumps(user))
        db.session.add(oauth_user)
        db.session.commit()

    return redirect('/')


@app.route('/logout')
def logout():
    user = 'Guest'
    if 'username' in session:
        session.pop('username')
        session.pop('user')
    return redirect('/')


# 显示用户详情


@app.route('/user/<nickname>')
@login_required
def user(nickname):
    user = models.User.query.filter_by(nickname=nickname).first()
    if user == None:
        flash('User ' + nickname + ' not found.')
        return redirect(url_for('index'))
    posts = [
        {'author': user, 'body': 'Test post #1'},
        {'author': user, 'body': 'Test post #2'}
    ]
    return render_template('user.html',
                           user=user,
                           posts=posts)


# 上传文件


UPLOAD_FOLDER = 'app/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'JPG', 'JPEG'])

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return 'ok'  # redirect(url_for('uploaded_file',filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''


# 浏览上传的文件


from flask import send_from_directory


@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)


# 列出给定目录下的文件名


@app.route('/imageslist/<file_dir>')
def file_name(file_dir):
    file_dir = 'uploads'
    lists = []
    li = ''

    for root, dirs, files in os.walk(file_dir):
        for file in files:
            lists.append(os.path.join(root, file))
            li += '<li><a href="/' + os.path.join(root, file) + ' "> ' + file + '</a></li>'

    return '''
    <!doctype html>
    <title>images list</title>
    <h1>imageslist</h1>
    <ul>
      ''' + li + '''
    </ul>
    </form>
    '''
